<?php
namespace app\common\utils;


class AideUtil
{
    /**
     * 限速功能
     * @param string $key session 键
     * @param int $num 单位时间内执行次数
     * @param int $term 单位时间
     * @return bool
     */
    public function setLimit(string $key, int $num = 5, int $term = 900){
        $session = app()->session;
        if( !$session->has($key) ){
            $arr = [
                'start' => time(),
                'count' => 0,
                'term' => $term
            ];
            $session->set($key, $arr);
        }
        $data = $session->get($key);

        //判断在一定时间内是否超过限制
        if($data['count'] >= $num && ( time() - $data['start'] ) < $data['term']){
            return false;
        }
        //重新记录
        if( $data['count'] >= $num ){
            $data['start'] = time();
            $data['count'] = 0;
        }
        $data['count']++; //发送一次递增一次
        //保存回session
        $session->set($key, $data);
        return true;
    }
}